<template>
    <div>
        <div class="tab-container">
            <div v-for="(tab, index) in tabs" :key="index" :class="['tab-item', { 'active': activeTab === index }]"
                @click="changeTab(index)">
                {{ tab }}
            </div>
        </div>

        <!-- 当选中历届展会包时显示表单 -->
        <div v-if="activeTab === 0" class="form-container">
            <div class="form-item">
                <label>展会时间</label>
                <el-select v-model="selectedYear" placeholder="请选择时间" style="width: 567px;"
                    @change="fetchExhibitionInfo">
                    <el-option v-for="year in availableYears" :key="year" :label="year.year" :value="year.year" />
                </el-select>
            </div>
            <div class="form-item">
                <label>展会信息</label>
                <el-select v-model="selectedExhibitions" multiple collapse-tags collapse-tags-tooltip
                    @change="calculateExhibitionCost" style="width: 567px;" placeholder="请选择展会">
                    <!-- 2已购买，1未付款， 0未购买 -->
                    <el-option v-for="item in ExhibitList" :key="item.exhibitionName" :disabled="item.isOwn === 2"
                        :label="item.vipContent" :value="item.tid" />
                </el-select>
            </div>
        </div>
        <!-- 地区客源包 -->
        <div v-if="activeTab === 1" class="form-container">
            <div class="form-item">
                <label>地区信息</label>
                <el-cascader :options="options" v-model="selectedRegion" placeholder="请选择地区" ref="cascaderRef"
                    style="width: 567px;" :props="props1" @change="handleChange" :show-all-levels="false"
                    class="custom-cascader" />
            </div>

        </div>
        <!-- 早鸟展会包 -->
        <div v-if="activeTab === 2" class="form-container">
            <div class="form-item">
                <label>展会信息</label>
                <el-select v-model="selectedEarlyBirdExhibitions" multiple collapse-tags collapse-tags-tooltip
                    style="width: 567px;" placeholder="请选择展会信息 " @change="calculateExhibitionCost">
                    <el-option v-for="item in exhibitionInfo" :key="item.value" :label="item.vipContent"
                        :value="item.tid" />
                </el-select>
            </div>
        </div>
        <div class="tab-container cl_bot">
            <div class="form-item talCost">
                <label style="font-size: 16px;margin-right: 0">解锁次数：</label>
                <b style="font-size: 16px;">{{ unlockTime }}</b>
            </div>
            <div class="form-item talCost" style="padding-left: 12px;">
                <label>应付费用：</label>
                <span>￥{{ earlyBirdTotalCost }}</span>
            </div>
            <div class="form-item">
                <el-button type="primary" @click="payEarlyBirdFee" :disabled="earlyBirdTotalCost === 0">
                    立即支付
                </el-button>
            </div>
        </div>

    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import baseService from "@/service/baseService";
import { ElMessage } from "element-plus";
const router = useRouter();
const options = ref([]);
const selectedRegion = ref([]);
// 定义选项卡列表
const tabs = ref(['历届展会包', '地区客源包', '早鸟展会包']);
// 定义当前选中的选项卡索引
const activeTab = ref(0);
const props1 = {
    checkStrictly: true,
    multiple: true,
    label: 'name',  // 将显示字段改为 name
    value: 'code',   // 将值字段改为 code
    disabled: (data) => data.isOwn === 2 || data.lockFlag == 2

};

// 存储选中的年份
const selectedYear = ref("");
const vipcode = ref([]);
// 存储获取到的历届展会信息
const exhibitionInfo = ref<{ value: string; label: string }[]>([]);
const ExhibitList = ref<string[]>([]);
// 存储选中的历届展会信息
const selectedExhibitions = ref<string[]>([]);
// 存储获取到的早鸟展会信息
const earlyBirdExhibitionInfo = ref<{ value: string; label: string }[]>([]);
// 存储选中的早鸟展会信息
const selectedEarlyBirdExhibitions = ref<string[]>([]);
// 早鸟展会包应付费用
const earlyBirdTotalCost = ref(0);
const unlockTime = ref(0);
// 定义可选年份列表，这里以 2020 年到当前年份为例
const currentYear = new Date().getFullYear();
const availableYears = ref<string[]>([]);
const vipid = ref([]);
const level = ref([]);
// 切换选项卡的方法
const changeTab = (index: number) => {
    activeTab.value = index;
    resetFormState();
};

// 重置表单状态
const resetFormState = () => {
    earlyBirdTotalCost.value = 0;
    selectedExhibitions.value = [];
    selectedEarlyBirdExhibitions.value = [];
    selectedYear.value = "";
    unlockTime.value = 0;
    selectedRegion.value = []
    vipid.value = [];
};
//处理地区信息 禁用状态与价格计算
const handleChange = (val) => {
    console.log(val)
    let total = 0;
    let list = 0
    let vipcodes = []
    let vipids = []
    let levels = []

    // 重置所有节点lockFlag
    options.value.forEach(item => {
        if (item && typeof item === 'object') {
            item.lockFlag = 0; // 默认父节点lockFlag=0
            if (Array.isArray(item.children)) {
                item.children.forEach(child => {
                    if (child && typeof child === 'object') {
                        child.lockFlag = 0; // 默认子节点lockFlag=0
                    }
                });
            }
        }
    });

    // 处理选中值
    val.forEach((item) => {
        if (item.length === 1) {
            // 选择父节点: 子节点全部lockFlag=0
            options.value.forEach((parent) => {
                if (parent.code === item[0]) {
                    total += parent.vipPrice || 0;
                    list += parent.vipCount || 0;
                    vipids.push(parent.vipId);
                    vipcodes.push(parent.code);
                    levels.push("2");

                    // 设置所有子节点lockFlag=0
                    if (Array.isArray(parent.children)) {
                        parent.children.forEach(child => {
                            child.lockFlag =2;
                        });
                    }
                }
            });
        } else if (item.length === 2) {
            // 选择子节点: 父节点lockFlag=2
            options.value.forEach((parent) => {
                if (parent.code === item[0]) {
                    parent.lockFlag = 2; // 父节点lockFlag=2

                    parent.children.forEach((child) => {
                        if (child.code === item[1]) {
                            total += child.vipPrice || 0;
                            list += child.vipCount || 0;
                            vipids.push(child.vipId);
                            vipcodes.push(child.code);
                            levels.push("3");
                            child.lockFlag = 0; // 选中的子节点lockFlag=0
                        }
                    });
                }
            });
        }
    });

    // 处理取消子节点选择时父节点状态
    options.value.forEach(parent => {
        if (parent.children && Array.isArray(parent.children)) {
            const hasSelectedChild = val.some(item =>
                item.length === 2 && item[0] === parent.code
            );
            if (!hasSelectedChild) {
                parent.lockFlag = 0; // 没有选中子节点时父节点lockFlag=0
            }
        }
    });

    unlockTime.value = list;
    earlyBirdTotalCost.value = total;
    vipid.value = vipids;
    vipcode.value = vipcodes;
    level.value = levels;

}
// 根据选择的年份请求展会信息
const fetchExhibitionInfo = async () => {
    if (!selectedYear.value) return;
    // 清空之前的选中数据
    selectedExhibitions.value = [];
    // 再获取展会列表
    baseService.post('/noc/vip/queryExhibitionListByYear', {
        year: selectedYear.value
    }).then((res) => {
        if (res.code == 0) {
            ExhibitList.value = res.data || [];  // 存储完整地区数据
        }
    });
};
//
const fetchYear = async () => {
    baseService.get('/noc/companybasicinfo/queryExhibitionYear', {}).then((res) => {
        if (res.code == 0) {
            availableYears.value = res.data || [];  // 存储完整地区数据
        }
    })
    // 地区信息
    baseService.get('/noc/basearea/getCompanyBasicInfoCity', {}).then((res) => {
        if (res.code == 0) {
            options.value = res.list[0].children || [];  // 存储完整地区数据
        }
    });
    // 早鸟展会信息
    baseService.get('/noc/vip/getZaoniaoBag', {}).then((res) => {
        if (res.code == 0) {
            exhibitionInfo.value = res.data || [];  // 存储完整地区数据
        }
    });
};

// 添加历届展会包价格计算方法
const calculateExhibitionCost = () => {
    let total = 0;
    let list = 0
    let vipids = []
    // 遍历选中的展会id，累加对应价格
    if (activeTab.value === 0) {
        selectedExhibitions.value.forEach(id => {
            const exhibition = ExhibitList.value.find(item => item.tid === id);
            if (exhibition) {
                total += exhibition.vipPrice || 0;
                list += exhibition.vipCount || 0;
                vipids.push(exhibition.id);
            }
        });
    } else if (activeTab.value === 2) {
        selectedEarlyBirdExhibitions.value.forEach(id => {
            const exhibition = exhibitionInfo.value.find(item => item.tid === id);
            if (exhibition) {
                total += exhibition.vipPrice || 0;
                list += exhibition.vipCount || 0;
                vipids.push(exhibition.id);
            }
        });
    }

    unlockTime.value = list;
    earlyBirdTotalCost.value = total;
    vipid.value = vipids;
};
// 支付费用
const payEarlyBirdFee = () => {
    console.log("-----------------------------", selectedYear.value);
    console.log("----------------11-------------", activeTab.value);
    let exhibitionstatus = 0;
    if (selectedYear.value == "2025" || activeTab.value == 2) {
        exhibitionstatus = 1;
    }
    console.log("支付早鸟展会包费用:", earlyBirdTotalCost.value);
    let pan = {}
    if (activeTab.value == 0 || activeTab.value == 2) {
        pan = {
            tid: activeTab.value == 0 ? selectedExhibitions.value.join(',') : selectedEarlyBirdExhibitions.value.join(','),
            unlockTime: unlockTime.value,
            price: earlyBirdTotalCost.value,
            vipId: vipid.value.join(','),
            exhibitionstatus,

        }
    } else if (activeTab.value == 1) {
        pan = {
            unlockTime: unlockTime.value,
            level: level.value.join(','),
            price: earlyBirdTotalCost.value,
            area: vipcode.value.join(','),
            vipId: vipid.value.join(','),
            exhibitionstatus,
        }
    }
    console.log(pan)
    baseService.post('/noc/vip/order/save', pan).then((res) => {
        if (res.data.contain == "false") {
            ElMessage.error("无权购买" + res.data.exhibitionName + "，请联系业务员！");
        }

        if (res.code == 0) {
            //   options.value = res.data || [];  // 存储完整地区数据
            router.push({
                path: '/order-confirm',
                query: {
                    Text: activeTab.value === 1 ? '地区客源包' : activeTab.value === 0 ? '历届展会包' : "早鸟展会包",
                    orderNum: res.data.order.orderNum,
                    vipType: res.data.userVip.area
                }
            })
        }
    });
    // router.push('/order-confirm');
    // 这里可以添加实际的支付逻辑
};
// 计算早鸟展会包应付费用
const calculateEarlyBirdCost = () => {
    //   earlyBirdTotalCost.value = earlyBirdExhibitionInfo.value

};

onMounted(() => {
    // 组件挂载时生成随机颜色
    fetchYear();
});
</script>

<style lang="less" scoped>
.tab-container {
    width: 100%;
    flex-direction: row;
    display: flex;
    /* 修改为横向排列 */
}

.tab-item {
    flex: 1;
    /* 使每个选项卡平均分配宽度 */
    text-align: center;
    padding: 10px;

    font-size: 16px;
    cursor: pointer;
}

.cl_bot {
    text-align: right;
    font-size: 16px;
    position: absolute;
    bottom: 30px;
    right: 43px;
    width: auto;

    .talCost {
        span {
            color: rgba(255, 46, 46, 1);
            padding-right: 20px;
        }
    }
}


.tab-item.active {
    background: url("@/assets/images/Vector.png") no-repeat center bottom;
    color: #1677FF;
    font-weight: bold;
}

.form-container {
    padding: 38px;
}

.form-item {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
}

.form-item label {
    width: 80px;
    font-size: 16px;
    margin-right: 10px;
}

.talCost {
    label {
        font-size: 16px;
    }

    span {
        font-size: 32px;

    }
}
</style>
